package com.choosefine.it.common.excel;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.choosefine.it.common.utils.ExcelUtils;

/**
 * 将数据库中的数据导出到Excel中
 * 
 * @author liaozhanggen 2017年1月6日
 */
public class ExportExcel<T> {
	
	private static Logger logger = LoggerFactory.getLogger(ExportExcel.class);

	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	
	public ExportExcel(){
		
	}
	

	/**
	 * 将指定的表头，发生成Excel模板
	 * 
	 * @param title
	 *            表格名称
	 * @param headers
	 *            表格列名数组
	 * @param fileName
	 *            输出流
	 * @throws FileNotFoundException 
	 */
	@Deprecated
	public static void buildExcelTemplate(String title, String[] headers,String fileName) throws FileNotFoundException{
		logger.info("----start----buildExcelTemplate------------->");
		//生成目录
		ExcelUtils.mkdirFile(fileName);
		File file = new File(fileName);
		file.setReadable(false);
 
		FileOutputStream outputStream = new FileOutputStream(file);
		
		//生成一个工作薄
		Workbook workbook = new HSSFWorkbook();
		//统一设置字体
		setWorkBookFont(workbook);
		
		// 生成一个表格
		Sheet sheet = workbook.createSheet(title);
		sheet.createFreezePane(0, 1);;//冻结坐标
		
		// 生成标题行
		Row row = sheet.createRow(0);

		for (int i = 0; i < headers.length; i++) {
			
			Cell cell = row.createCell(i);
			HSSFRichTextString text = new HSSFRichTextString(headers[i]);
			cell.setCellValue(text);
			
			//生成一个字体
			Font font=workbook.createFont();
			font.setColor(HSSFColor.BLACK.index);//HSSFColor.VIOLET.index //字体颜色
			font.setFontName("黑体");
			font.setFontHeightInPoints((short)240);
			font.setFontHeight((short)240);
			
			CellStyle style = cell.getCellStyle();
			style.setFont(font);
		}
		
		try {
			workbook.write(outputStream);
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != outputStream) {
					outputStream.flush();
					outputStream.close();
				}
				if (null != workbook) {
					workbook.close();
					logger.info("----close----buildExcelTemplate------------->");
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			file = null;
		}
		logger.info("----end----buildExcelTemplate------------->");
	}


	/**
	 * 统一设置字体
	 * 
	 * @author liaozhanggen 2017年1月9日
	 */
	private static void setWorkBookFont(Workbook workbook) {
		//统一设置字体
		CellStyle style = workbook.createCellStyle();
		
		//生成一个字体
		Font font=workbook.createFont();
		font.setColor(HSSFColor.BLACK.index);//HSSFColor.VIOLET.index //字体颜色
		font.setFontName("黑体");
		font.setFontHeightInPoints((short)240);
		font.setFontHeight((short)240);
		style.setFont(font);
	}
	
	/**
	 * 将数据导入到表格
	 * 
	 * @param title
	 *            表格名称
	 * @param headers
	 *            表格列名数组
	 * @param dataset
	 *            数据集合
	 * @param out
	 *            输出流
	 * @param pattern
	 *            有其他格式的设定输出格式
	 * @throws FileNotFoundException 
	 */

	@SuppressWarnings("unchecked")
	public void exportExcel(String title, String[] headers, Collection<T> dataset,String fileName) throws FileNotFoundException {
		logger.info("-------exportExcel----------->" + fileName);
		//生成目录结构
		ExcelUtils.mkdirFile(fileName);
		File file = new File(fileName);
		file.setReadable(false);
 
		FileOutputStream out = new FileOutputStream(file);
		
		// 生成一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个表格
		HSSFSheet sheet = workbook.createSheet(title);
		// 生成标题行
		HSSFRow row = sheet.createRow(0);

		for (int i = 0; i < headers.length; i++) {
			HSSFCell cell = row.createCell(i);
			HSSFRichTextString text = new HSSFRichTextString(headers[i]);
			cell.setCellValue(text);
		}

		// 遍历集合，获取当中的数据
		Iterator<T> it = dataset.iterator();
		int index = 0;

		while (it.hasNext()) {
			index++;
			row = sheet.createRow(index);
			T t = it.next();
			// 利用反射，根据javabean属性的先后顺序，动态调用getXxx()方法得到属性值
			Field[] fields = t.getClass().getDeclaredFields();
			
			// 根据属性名获取属性值
			for (int i = 0; i < fields.length; i++) {
				HSSFCell cell = row.createCell(i);
				Field field = fields[i];
				
				// 获取属性名
				String fieldName = field.getName();
				// 获取属性值

				String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
				Class tCls = t.getClass();

				try {
					Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
					Object value = getMethod.invoke(t, new Object[] {});
					String textValue = null;

					if (value instanceof Date) {
						Date date = (Date) value;
						textValue = sdf.format(date);
					} else {
						textValue = value != null ? value.toString() : "";
					}

					if (textValue != null) {

						// 是数字当做double处理
						Pattern p = Pattern.compile("^//d+(//.//d+)?$");
						Matcher matcher = p.matcher(textValue);

						if (matcher.matches()) {
							cell.setCellValue(Double.parseDouble(textValue));

						} else {
							HSSFRichTextString richString = new HSSFRichTextString(textValue);
							cell.setCellValue(richString);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		try {
			workbook.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
